<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>parseStr</title>
</head>

<body>
    <h1>解析json</h1>
    <div id="result-json">....</div>
    <button type="button" id="testJson">点击我解析json数据</button>
    <h1>解析javascript值</h1>
    <div id="result-eval">...</div>
    <button type="button" id="testEval">点击我解析javascript值</button>
    <script>
        const parseStr = (str, type = 'json') => {
            const parseMethod = {
                'eval': (v) => new Function(`return ${v}`)(),
                'json': JSON.parse
            }
            let res = null;
            try {
                const method = parseMethod[type];
                if (method) {
                    res = method(str);
                }
            } catch (error) {
                console.error(`[parse data error]:${error}`);
            }
            return res;
        }
        const resJson = document.getElementById('result-json');
        const btnJson = document.getElementById('testJson');
        const resEval = document.getElementById('result-eval');
        const btnEval = document.getElementById('testEval');

        btnJson.onclick = () => {
            const str = `{"name":"张三","age":18}`;
            resJson.innerText = `正在解析${str}中`;
            const res = parseStr(str);
            setTimeout(() => {
                resJson.innerText = `解析结果为:${JSON.stringify(res)}`;
            }, 3000);
        }
        btnEval.onclick = () => {
            const str = `1 + 1`;
            resEval.innerText = `正在解析${str}中`;
            const res = parseStr(str, 'eval');
            setTimeout(() => {
                resEval.innerText = `解析结果为:${res}`;
            }, 3000);
        }
    </script>
</body>

</html>